package com.jck.wx.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.sql.PagerUtils;
import com.jck.config.WeixinApiConfig;
import com.jck.dplus.common.annomapper.MybatisBaseDaoCRUD;
import com.jck.dplus.common.utils.util.ChkUtil;
import com.jck.dplus.common.utils.util.PageBean;
import com.jck.dplus.common.utils.util.PageList;
import com.jck.wx.data.AddUserData;
import com.jck.wx.entity.AddUser;
import com.jck.wx.entity.AddUserWx;
import com.jck.wx.util.PageUtils;
import com.jck.wx.util.Query;
import com.jck.wx.util.R;

import lombok.extern.slf4j.Slf4j;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;
import weixin.popular.bean.user.User;

@Slf4j
@Controller
@RequestMapping("/addmtg")
/**
 * 微信授权，参会数据绑定
 * @author Administrator
 *
 */
public class WxAddMtgController {

	@Autowired
	public MybatisBaseDaoCRUD mBaseDao;
	@Autowired
	public WeixinApiConfig weixinApiConfig;

	/**
	 * 微信网页授权 code->AccessToken(openid)->获取用户信息
	 * 参会认证微信授权跳转页面
	 * @param res
	 * @param code
	 * @return
	 */
	@GetMapping("/redirectUrlInfoCertPage")
	public String redirectUrlInfoCertPage(HttpServletRequest res, String code, Map<String, Object> map, String oid) {
		oid = ChkUtil.isEmpty(oid) ? "" : oid;
		if (!ChkUtil.isEmpty(code)) {
			SnsToken snsToken = SnsAPI.oauth2AccessToken(weixinApiConfig.getAPPID(), weixinApiConfig.getAPPSECRET(),
					code);
			if (snsToken.isSuccess()) {
				User u = SnsAPI.userinfo(snsToken.getAccess_token(), snsToken.getOpenid(), weixinApiConfig.getLANG());
				if (u.isSuccess()) {
					String sql = "select * from addmtg_addUserWx where appid='" + weixinApiConfig.getAPPID()
							+ "' and openid='" + snsToken.getOpenid() + "'";
					AddUserWx auwx = (AddUserWx) mBaseDao.findBySqlUniqueObject(sql, AddUserWx.class, null);
					if (auwx == null) {
						auwx = new AddUserWx();
						try {
							BeanUtils.copyProperties(auwx, u);
							auwx.setAppid(weixinApiConfig.getAPPID());
							Date date = new Date();
							auwx.setCreateTime(date);
							auwx.setUpdateTime(date);
							mBaseDao.saveObject(auwx);

						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
					res.getSession().setAttribute(snsToken.getOpenid(), snsToken);
					res.getSession().setAttribute("oid", snsToken.getOpenid());
					map.put("oid", snsToken.getOpenid());
				}

				return "modules/addmtg/addInfoCert";
			} else {
				return "404";
			}

		} else {
			if (!ChkUtil.isEmpty(oid)) {
				SnsToken snsToken = (SnsToken) res.getSession().getAttribute(oid);
				if (snsToken != null) {
					User u = SnsAPI.userinfo(snsToken.getAccess_token(), snsToken.getOpenid(),
							weixinApiConfig.getLANG());
					if (u.isSuccess()) {
						String sql = "select * from addmtg_addUserWx where appid='" + weixinApiConfig.getAPPID()
								+ "' and openid='" + snsToken.getOpenid() + "'";
						AddUserWx auwx = (AddUserWx) mBaseDao.findBySqlUniqueObject(sql, AddUserWx.class, null);
						if (auwx == null) {
							auwx = new AddUserWx();
							try {
								BeanUtils.copyProperties(auwx, u);
								auwx.setAppid(weixinApiConfig.getAPPID());
								Date date = new Date();
								auwx.setCreateTime(date);
								auwx.setUpdateTime(date);
								mBaseDao.saveObject(auwx);

							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						} else {
							try {
								BeanUtils.copyProperties(auwx, u);
								Date date = new Date();
								auwx.setUpdateTime(date);
								mBaseDao.updateObject(auwx);
							} catch (IllegalAccessException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (InvocationTargetException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
						res.getSession().setAttribute(snsToken.getOpenid(), snsToken);
						res.getSession().setAttribute("oid", snsToken.getOpenid());
						map.put("oid", snsToken.getOpenid());
						return "modules/addmtg/addInfoCert";
					} else {
						return "404";
					}

				}

			} else {
				return "404";
			}

		}
		return "404";
	}
/**
 *微信 参会认证初始化授权
 * @param res
 * @param send
 * @return
 * @throws IOException
 */
	@GetMapping("/redirectUrl")
	public String redirectUrl(HttpServletRequest res, HttpServletResponse send) throws IOException {
		String redirect_uri = "http://" + weixinApiConfig.getREDIRECTDOMAINNAME() + "/addmtg/redirectUrlInfoCertPage";
		String url = SnsAPI.connectOauth2Authorize(weixinApiConfig.getAPPID(), redirect_uri, true, null);
		res.setAttribute("url", url);
		return "redirectUrl";
	}
	
	/**
	 * 微信 授权-查询参会认证信息
	 * @param res
	 * @param send
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/redirectUrlByFindData")
	public String redirectUrlByFindData(HttpServletRequest res, HttpServletResponse send) throws IOException {
		String redirect_uri = "http://" + weixinApiConfig.getREDIRECTDOMAINNAME() + "/addmtg/findAddMtgPage";
		String url = SnsAPI.connectOauth2Authorize(weixinApiConfig.getAPPID(), redirect_uri, true, null);
		res.setAttribute("url", url);
		return "redirectUrl";
	}
   /**
              * 完善信息页面
    * @param res
    * @param oid
    * @return
    */
	@GetMapping("/addFullInfoPage")
	public String addFullInfoPage(HttpServletRequest res, String oid) {
		Map map = new HashMap();
		map.put("oid", oid);
		return "modules/addmtg/addFullInfo";
	}
     /**
      * 保存参会认证数据
      * @param res
      * @param adduser
      * @return
      */
	@PostMapping("/addInfoCert")
	@ResponseBody
	public Map addInfoCert(HttpServletRequest res, @RequestBody AddUserData adduser) {
		Map map = new HashMap();
		map.put("code", -1);
		map.put("msg", "参数要必填");
		if (ChkUtil.isEmpty(adduser.getOpenid())) {
			map.put("code", 1);
			map.put("msg", "请使用微信授权");
			return map;
		}

		String sql = "select * from addmtg_addUser where 1=1   ";

		if (!ChkUtil.isEmpty(adduser.getName()) && !ChkUtil.isEmpty(adduser.getMobile())) {
			sql += " and name=#{pojo.name} and mobile like #{pojo.mobilePre} and mobile like #{pojo.mobileSub}";
			map.put("name", adduser.getName());
			String mobilePre = adduser.getMobile().substring(0, adduser.getMobile().length() - 8);
			String mobileSub = adduser.getMobile().substring(adduser.getMobile().length() - 4,
					adduser.getMobile().length());
			map.put("mobilePre", mobilePre + "%");
			map.put("mobileSub", "%" + mobileSub);
			AddUser au = (AddUser) mBaseDao.findBySqlUniqueObject(sql, AddUser.class, map);

			AddUserWx auwx = (AddUserWx) mBaseDao.findBySqlUniqueObject(
					"select * from addmtg_addUserWx where openid='" + adduser.getOpenid() + "'", AddUserWx.class, null);
			map = new HashMap();
			if (au != null) {
				if (au.getStatus() == 1) {
					map.put("code", 0);
					map.put("msg", "已认证成功");
					return map;
				} else {
					au.setStatus(1);
					mBaseDao.updateObject(au);
					if (auwx != null) {
						auwx.setAddUserId(au.getId_());
						Date date = new Date();
						auwx.setUpdateTime(date);
						mBaseDao.updateObject(auwx);
					}

					map.put("code", 1);
					map.put("msg", "参会认证成功");
					return map;
				}

			} else {
				map.put("code", 2);
				map.put("msg", "没有报名");
				return map;
			}
		} else {
			map.put("code", -1);
			map.put("msg", "参数要必填");
			return map;
		}

	}
     /**
                     * 保存完善信息数据
      * @param res
      * @param adduser
      * @return
      */
	@PostMapping("/addFullInfo")
	@ResponseBody
	public Map addFullInfo(HttpServletRequest res, @RequestBody AddUserData adduser) {
		Map map = new HashMap();
		map.put("code", 0);
		map.put("msg", "ok");

		if (ChkUtil.isEmpty(adduser.getOpenid())) {
			map.put("code", 1);
			map.put("msg", "请使用微信授权");
			return map;
		}

		String sql = "select * from addmtg_addUserWx where 1=1 ";

		if (!ChkUtil.isEmpty(adduser.getOpenid())) {

			sql += " and appid='" + weixinApiConfig.getAPPID() + "' and openid='" + adduser.getOpenid() + "'";

			AddUserWx auwx = (AddUserWx) mBaseDao.findBySqlUniqueObject(sql, AddUserWx.class, null);
			sql = "select  * from addmtg_addUser where mobile='" + adduser.getMobile() + "'";
			AddUser au = (AddUser) mBaseDao.findBySqlUniqueObject(sql, AddUser.class, null);
			if (au != null) {
				map.put("code", 1);
				map.put("msg", "该手机号已报名使用。");
				return map;

			} else {
				if (auwx == null) {
					map.put("code", 1);
					map.put("msg", "请使用微信授权");
					return map;
				}
				au = new AddUser();
				au.setType(1);
				Date date = new Date();
				try {
					BeanUtils.copyProperties(au, adduser);
					au.setStatus(1);
					au.setCreateTime(date);
					au.setUpdateTime(date);
					mBaseDao.saveObject(au);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (auwx != null) {
					auwx.setMobile(au.getMobile());
					auwx.setAddUserId(au.getId_());
					auwx.setUpdateTime(date);
					mBaseDao.updateObject(auwx);

				}
				map.put("code", 0);
				map.put("msg", "报名成功");
				return map;
			}
		}
		return map;
	}

  /**
           * 查询认证数据
   * @param params
   * @return
   */
	@GetMapping("/findAddMtgData")
	@ResponseBody
	public R findAddMtgData(@RequestParam Map<String, Object> params) {
		PageList  pl=new PageList();
		PageUtils pageUtil=null;
		String sql = "SELECT * FROM  addmtg_addUser    WHERE 1=1 ";
		
		if (params.get("typeStatus") != null) {
			Integer typeStatus = Integer.parseInt(params.get("typeStatus").toString());
			if (typeStatus == 1) {// 报名未认证
				sql += "   and type=0 and status=0";// 报名未认证
			} else if (typeStatus == 2) {
				sql += "  and  type=0 and status=1";// 报名已认证
			} else {
				sql += "  and type=1 and status=1";// 报名完善信息
			}

		} else {
			sql += "  and  type=0 and status=0";// 报名未认证
		}
 
		  sql += Query.getLastSortSql(params, " order by updateTime desc");
		  pl = this.mBaseDao.findBySqlForPageList(sql, Map.class, Query.getPageBean(params), params);
		  pageUtil = new PageUtils(pl.getResultList(), pl.getPageBean().getTotalCount().intValue(),
		  pl.getPageBean().getPageSize(), pl.getPageBean().getPage());
		return R.ok().put("page", pageUtil);
	}
	/**
	 *  查询认证数页面
	 */
	@GetMapping("/findAddMtgPage")
	public String findAddMtgPage(HttpServletRequest res,String code) {
		String oid="";
		List<String> allowOids=Arrays.asList(weixinApiConfig.getAllowOids().split(","));
		if (!ChkUtil.isEmpty(code)) {
			SnsToken snsToken = SnsAPI.oauth2AccessToken(weixinApiConfig.getAPPID(), weixinApiConfig.getAPPSECRET(),
					code);
			if (!snsToken.isSuccess()||!SnsAPI.userinfo(snsToken.getAccess_token(), snsToken.getOpenid(), weixinApiConfig.getLANG()).isSuccess()) {
				return "404";
			}
			oid=snsToken.getOpenid();
			
			if(!allowOids.contains(oid)) {
				
				return "404";
			}

		}else {
			return "404";
		}
		
		return "modules/addmtg/findAddMtgPage";
	}

}